//
//  ZQHomeViewController.swift
//  新浪微博
//
//  Created by huami on 2019/10/10.
//  Copyright © 2019 huami. All rights reserved.
//

import UIKit

private let cellID = "cellID"

class ZQHomeViewController: ZQBaseViewController {
    // 列表的视图模型
    private lazy var listViewModel = ZQStatusListViewModle()
    private lazy var statusList = [String]()

    @objc private func showFriends() {
        print(#function)
        let vc = ZQDemoViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    override func loadData() {
//        print("准备刷新，最后一条\(self.listViewModel.statusList.last?.text ?? "")")
        listViewModel.loadStatus(pullup: isPullup) { _, shouldRefresh in

            print("加载数据结束")

            self.refreshControl?.endRefreshing()

            // 恢复上拉刷洗标志
            self.isPullup = false

            if shouldRefresh {
                self.tableView?.reloadData()

                print("刷新表格")
            }
        }
    }
}

// MARK: - 表格的数据源方法,具体的数据源方法实现，不需要super

extension ZQHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)

        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        return cell
    }
}

extension ZQHomeViewController {
    override func setupTableView() {
        super.setupTableView()
        // 设置导航栏
        //        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
        // swift 调用 oc 返回的instancetype 判断不出类型
        //        let btn: UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor:.darkGray, highlightedColor:.orange)
        //        btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)

        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))

        // 注册cell
//        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellID) 
        tableView?.register(UINib(nibName: "ZQStatusNormalCell", bundle: nil), forCellReuseIdentifier: cellID)
        setupNavTitle()
    }

    private func setupNavTitle() {
        let title = ZQNetWorkManager.shared.userAccount.screen_name
        let button = ZQTitleButton(title: title)

        navItem.titleView = button

        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }

    @objc func clickTitleButton(btn: UIButton) {
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
}
